<template>
  <div class="index-center-page">
    <div class="content-wrapper">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">价格指数</h1>
        <p class="page-description">
          价格指数是基于平台实际交易数据计算得出的市场参考指标，反映市场整体价格走势，供交易参考，该指数不代表具体市场价格，仅作为市场趋势的量化指标。
        </p>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-section">
        <div class="loading-text">正在加载指数数据...</div>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="error-section">
        <div class="error-text">{{ error }}</div>
        <button @click="fetchIndexData" class="retry-button">重试</button>
      </div>

      <!-- 指数数据卡片 -->
      <div class="index-cards">
        <div class="index-card">
          <div class="card-title">当日指数</div>
          <div class="card-value">{{ indexData.dailyIndex.value }}</div>
          <div class="card-change" :class="parseFloat(indexData.dailyIndex.change) >= 0 ? 'positive' : 'negative'">
            <span class="change-value"
              >{{ parseFloat(indexData.dailyIndex.change) >= 0 ? '+' : '' }}{{ indexData.dailyIndex.change }}</span
            >
            <span class="change-percent">{{ indexData.dailyIndex.percent }}%</span>
          </div>
        </div>

        <div class="index-card">
          <div class="card-title">7日均值</div>
          <div class="card-value">{{ indexData.weekAverage.value }}</div>
          <div class="card-change" :class="parseFloat(indexData.weekAverage.change) >= 0 ? 'positive' : 'negative'">
            <span class="change-value"
              >{{ parseFloat(indexData.weekAverage.change) >= 0 ? '+' : '' }}{{ indexData.weekAverage.change }}</span
            >
            <span class="change-percent">{{ indexData.weekAverage.percent }}%</span>
          </div>
        </div>

        <div class="index-card">
          <div class="card-title">30日均值</div>
          <div class="card-value">{{ indexData.monthAverage.value }}</div>
          <div class="card-change" :class="parseFloat(indexData.monthAverage.change) >= 0 ? 'positive' : 'negative'">
            <span class="change-value"
              >{{ parseFloat(indexData.monthAverage.change) >= 0 ? '+' : '' }}{{ indexData.monthAverage.change }}</span
            >
            <span class="change-percent">{{ indexData.monthAverage.percent }}%</span>
          </div>
        </div>
      </div>

      <!-- 30日价格指数走势图 -->
      <div class="chart-section">
        <h2 class="chart-title">30日价格指数走势</h2>
        <p class="chart-subtitle">综合指数、采购指数、销售指数对比</p>
        <div class="chart-container">
          <div ref="chartRef" class="chart"></div>
        </div>
      </div>

      <!-- 指数说明 -->
      <div class="explanation-section">
        <h2 class="explanation-title">指数说明</h2>
        <div class="explanation-content">
          <div class="explanation-item">
            <h3>数据来源</h3>
            <p>基于平台实际成交的交易数据</p>
          </div>
          <div class="explanation-item">
            <h3>计算方法</h3>
            <p>采用加权平均算法，考虑交易量、时间等多个因素</p>
          </div>
          <div class="explanation-item">
            <h3>更新频率</h3>
            <p>每日更新，反映新市场动态</p>
          </div>
          <div class="explanation-item">
            <h3>参考价值</h3>
            <p>可作为市场价格趋势的重要参考指标</p>
          </div>
          <div class="explanation-item">
            <h3>使用建议</h3>
            <p>建议结合具体交易场景和实际市场情况使用该指数</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
// @ts-ignore
import * as echarts from 'echarts'
import { getIndexListApi } from '~/server/homeApi'

// 页面标题
useHead({
  title: '昌欣指数 - 价格指数',
  meta: [{ name: 'description', content: '昌欣菌业交易中心价格指数，基于平台实际交易数据计算的市场参考指标' }],
})

// 指数数据 - 将从API计算得出
const indexData = ref({
  dailyIndex: {
    value: '0',
    change: '0',
    percent: '0',
  },
  weekAverage: {
    value: '0',
    change: '0',
    percent: '0',
  },
  monthAverage: {
    value: '0',
    change: '0',
    percent: '0',
  },
})

// 计算指数统计数据
const calculateIndexStats = (data: any[]) => {
  if (data.length === 0) return

  const values = data.map((item) => parseFloat(item.compositeIndex))
  const today = values[values.length - 1] // 最新一天的数据
  const yesterday = values[values.length - 2] || today // 前一天的数据

  // 当日指数
  const dailyChange = today - yesterday
  const dailyPercent = yesterday > 0 ? ((dailyChange / yesterday) * 100).toFixed(2) : '0'

  // 7日均值
  const weekData = values.slice(-7)
  const weekAvg = weekData.reduce((sum, val) => sum + val, 0) / weekData.length
  const weekPrevData = values.slice(-14, -7)
  const weekPrevAvg =
    weekPrevData.length > 0 ? weekPrevData.reduce((sum, val) => sum + val, 0) / weekPrevData.length : weekAvg
  const weekChange = weekAvg - weekPrevAvg
  const weekPercent = weekPrevAvg > 0 ? ((weekChange / weekPrevAvg) * 100).toFixed(2) : '0'

  // 30日均值
  const monthAvg = values.reduce((sum, val) => sum + val, 0) / values.length
  const monthPrevData = values.slice(0, Math.floor(values.length / 2))
  const monthPrevAvg =
    monthPrevData.length > 0 ? monthPrevData.reduce((sum, val) => sum + val, 0) / monthPrevData.length : monthAvg
  const monthChange = monthAvg - monthPrevAvg
  const monthPercent = monthPrevAvg > 0 ? ((monthChange / monthPrevAvg) * 100).toFixed(2) : '0'

  indexData.value = {
    dailyIndex: {
      value: today.toFixed(2),
      change: dailyChange.toFixed(2),
      percent: dailyPercent,
    },
    weekAverage: {
      value: weekAvg.toFixed(2),
      change: weekChange.toFixed(2),
      percent: weekPercent,
    },
    monthAverage: {
      value: monthAvg.toFixed(2),
      change: monthChange.toFixed(2),
      percent: monthPercent,
    },
  }
}

// API相关状态
const loading = ref(false)
const apiData = ref<any[]>([])
const error = ref<string>('')

// 获取指数列表数据
const fetchIndexData = async () => {
  try {
    loading.value = true
    error.value = ''

    // 设置查询参数 - 获取最近30天的数据
    const endDate = new Date()
    const startDate = new Date()
    startDate.setDate(endDate.getDate() - 30)

    const params = {
      startDate: startDate.toISOString().split('T')[0], // YYYY-MM-DD格式
      endDate: endDate.toISOString().split('T')[0],
    }

    const response = await getIndexListApi(params)

    // 根据项目的HTTP拦截器，API成功时直接返回data字段的内容
    if (Array.isArray(response)) {
      apiData.value = response

      // 处理数据为图表格式
      chartData.value = processApiDataForChart(response)

      // 计算指数统计数据
      calculateIndexStats(response)

      // 重新初始化图表
      nextTick(() => {
        initChart()
      })
    } else {
      console.warn('API返回数据格式异常:', response)
      error.value = 'API返回数据格式异常'
    }
  } catch (err) {
    console.error('获取指数数据失败:', err)
    error.value = '获取指数数据失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 图表数据 - 将从API获取
const chartData = ref<any[]>([])

// 处理API数据为图表格式
const processApiDataForChart = (apiData: any[]) => {
  return apiData.map((item) => {
    const date = item.indexDate.split('-').slice(1).join('-') // 转换为 MM-DD 格式
    const value = parseFloat(item.compositeIndex) // 使用综合指数作为图表数据
    return {
      date,
      value,
      originalDate: item.indexDate,
      purchaseIndex: parseFloat(item.purchaseIndex),
      salesIndex: parseFloat(item.salesIndex),
      compositeIndex: parseFloat(item.compositeIndex),
    }
  })
}

const chartRef = ref<HTMLElement>()

// 初始化图表
const initChart = () => {
  if (!chartRef.value || chartData.value.length === 0) return

  const chart = echarts.init(chartRef.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        lineStyle: {
          color: '#999',
          width: 1,
          type: 'dashed',
        },
        crossStyle: {
          color: '#999',
        },
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#ddd',
      borderWidth: 1,
      textStyle: {
        color: '#333',
        fontSize: 12,
      },
      padding: [8, 12],
      formatter: function (params: any[]) {
        let result = `<div style="font-weight: 600; margin-bottom: 4px;">${params[0].axisValue}</div>`
        params.forEach((param: any) => {
          const color = param.color
          const name = param.seriesName
          const value = param.value
          result += `<div style="margin: 2px 0;">
            <span style="display: inline-block; width: 10px; height: 10px; background-color: ${color}; border-radius: 50%; margin-right: 6px;"></span>
            <span style="font-weight: 500;">${name}:</span>
            <span style="margin-left: 4px; font-weight: 600;">${value.toFixed(2)}</span>
          </div>`
        })
        return result
      },
    },
    grid: {
      left: '8%',
      right: '6%',
      bottom: '12%',
      top: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: chartData.value.map((item) => item.date),
      axisLine: {
        lineStyle: {
          color: '#ddd',
          width: 1,
        },
      },
      axisTick: {
        show: true,
        length: 4,
        lineStyle: {
          color: '#ddd',
        },
      },
      axisLabel: {
        color: '#666',
        fontSize: 11,
        margin: 15,
        interval: 'auto', // 自动计算间隔
        rotate: 0,
        formatter: function (value: string, index: number) {
          // 根据数据长度智能显示标签
          const totalData = chartData.value.length
          if (totalData <= 10) {
            // 数据很少时，显示所有标签
            return value
          } else if (totalData <= 20) {
            // 数据较少时，每隔1个显示一个
            return index % 2 === 0 ? value : ''
          } else if (totalData <= 30) {
            // 数据中等时，每隔2个显示一个
            return index % 3 === 0 ? value : ''
          } else {
            // 数据较多时，每隔4个显示一个
            return index % 4 === 0 ? value : ''
          }
        },
      },
    },
    yAxis: {
      type: 'value',
      min:
        chartData.value.length > 0
          ? Math.floor(
              Math.min(
                ...chartData.value.map((item) => item.compositeIndex),
                ...chartData.value.map((item) => item.purchaseIndex),
                ...chartData.value.map((item) => item.salesIndex),
              ) - 2,
            )
          : 80,
      max:
        chartData.value.length > 0
          ? Math.ceil(
              Math.max(
                ...chartData.value.map((item) => item.compositeIndex),
                ...chartData.value.map((item) => item.purchaseIndex),
                ...chartData.value.map((item) => item.salesIndex),
              ) + 2,
            )
          : 120,
      interval: 2,
      axisLine: {
        lineStyle: {
          color: '#ddd',
          width: 1,
        },
      },
      axisTick: {
        show: true,
        length: 4,
        lineStyle: {
          color: '#ddd',
        },
      },
      axisLabel: {
        color: '#666',
        fontSize: 12,
        margin: 12,
        formatter: function (value: number) {
          return value.toFixed(0)
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed',
        },
      },
    },
    series: [
      {
        name: '综合指数',
        type: 'line',
        data: chartData.value.map((item) => item.compositeIndex),
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          color: '#e93323',
          width: 3,
          type: 'solid', // 实线
        },
        itemStyle: {
          color: '#e93323',
          borderColor: '#fff',
          borderWidth: 2,
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(233, 51, 35, 0.15)',
              },
              {
                offset: 1,
                color: 'rgba(233, 51, 35, 0.05)',
              },
            ],
          },
        },
      },
      {
        name: '采购指数',
        type: 'line',
        data: chartData.value.map((item) => item.purchaseIndex),
        smooth: true,
        symbol: 'diamond',
        symbolSize: 7,
        lineStyle: {
          color: '#1890ff',
          width: 2.5,
          type: 'solid', // 实线
        },
        itemStyle: {
          color: '#1890ff',
          borderColor: '#fff',
          borderWidth: 2,
        },
        emphasis: {
          itemStyle: {
            color: '#1890ff',
            borderColor: '#fff',
            borderWidth: 3,
            shadowBlur: 10,
            shadowColor: 'rgba(24, 144, 255, 0.5)',
          },
        },
      },
      {
        name: '销售指数',
        type: 'line',
        data: chartData.value.map((item) => item.salesIndex),
        smooth: true,
        symbol: 'rect',
        symbolSize: 6,
        lineStyle: {
          color: '#52c41a',
          width: 2,
          type: 'dotted', // 点线
        },
        itemStyle: {
          color: '#52c41a',
          borderColor: '#fff',
          borderWidth: 2,
        },
      },
    ],
  }

  chart.setOption(option)

  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

onMounted(async () => {
  // 调用API获取数据，图表会在数据获取成功后自动初始化
  await fetchIndexData()
})
</script>

<style scoped lang="scss">
.index-center-page {
  min-height: 100vh;
  background-color: #ffffff;
  padding: 40px 0;
  margin: 20px 0;
  width: 100vw;
  margin-left: calc(50% - 50vw);
  margin-right: calc(50% - 50vw);

  .content-wrapper {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px;
  }
}

.page-header {
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin: 0 0 15px 0;
}

.page-description {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.index-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.index-card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;

  &:hover {
    transform: translateY(-2px);
  }
}

.card-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
}

.card-value {
  font-size: 36px;
  font-weight: 700;
  color: #333;
  margin-bottom: 10px;
  font-family: 'D-DIN-PRO-600-SemiBold', sans-serif;
}

.card-change {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.change-value {
  font-size: 18px;
  font-weight: 600;
}

.change-percent {
  font-size: 14px;
  font-weight: 500;
}

.positive {
  color: #52c41a;
}

.negative {
  color: #ff4d4f;
}

.chart-section {
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.chart-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0 0 20px 0;
}

.chart-container {
  width: 100%;
  height: 600px;
}

.chart {
  width: 100%;
  height: 100%;
}

.explanation-section {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.explanation-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
}

.explanation-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.explanation-item {
  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 8px 0;
  }

  p {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
    margin: 0;
  }
}

// 加载和错误状态样式
.loading-section {
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-text {
  font-size: 16px;
  color: #666;
}

.error-section {
  background: #fff2f0;
  border: 1px solid #ffccc7;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  text-align: center;
}

.error-text {
  color: #ff4d4f;
  margin-bottom: 10px;
}

.retry-button {
  background: #e93323;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.retry-button:hover {
  background: #d42b1a;
}

// 响应式设计
@media (max-width: 768px) {
  .index-cards {
    grid-template-columns: 1fr;
  }

  .explanation-content {
    grid-template-columns: 1fr;
  }

  .page-header,
  .index-card,
  .chart-section,
  .explanation-section {
    padding: 20px;
  }
}
</style>
